package org.oslims.server.service.impl;

import java.util.List;

import net.sf.gilead.gwt.GwtConfigurationHelper;
import net.sf.gilead.gwt.PersistentRemoteService;

import org.hibernate.Session;
import org.oslims.client.GenericOSLimsException;
import org.oslims.client.service.ParameterService;
import org.oslims.domain.Parameter;
import org.oslims.server.dao.ParameterDao;
import org.oslims.server.dao.hbm.HbmParameterDao;
import org.oslims.server.dao.util.HibernateUtil;

import com.google.gwt.validation.client.interfaces.IValidator;
import com.google.gwt.validation.server.ServerValidator;

public class ParameterServiceImpl extends PersistentRemoteService implements ParameterService {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8775335968437798208L;

	ParameterDao parameterDao;

	IValidator<Parameter> parameterValidator = new ServerValidator<Parameter>();

	public ParameterServiceImpl() {
		parameterDao = new HbmParameterDao();

		net.sf.gilead.core.hibernate.HibernateUtil hibernateUtil = new net.sf.gilead.core.hibernate.HibernateUtil(HibernateUtil.getSessionFactory());
		setBeanManager(GwtConfigurationHelper.initGwtStatelessBeanManager(hibernateUtil));
	}

	@Override
	public List<Parameter> getAllParameter() {
		Session session = HibernateUtil.getSession();
		parameterDao.setSession(session);

		List<Parameter> result = parameterDao.findAllSorted("name");

		session.close();
		return result;
	}

	@Override
	public void saveOrUpdateParameter(Parameter parameter) throws GenericOSLimsException {

		if (parameterValidator.validate(parameter).size() == 0) {
			Session session = HibernateUtil.getSession();
			session.beginTransaction();
			try {
				parameterDao.setSession(session);
				parameterDao.makePersistent(parameter);
				session.getTransaction().commit();
			} catch (RuntimeException e) {
				session.getTransaction().rollback();
				throw new GenericOSLimsException("Parameter", "Name not unique");
			} finally {
				session.close();
			}

		}
	}

	@Override
	public List<Parameter> getAllParameters(int start, int length, String sortBy, boolean desc) {
		Session session = HibernateUtil.getSession();
		parameterDao.setSession(session);

		List<Parameter> result = parameterDao.findAll(start, length, sortBy, desc);

		session.close();
		return result;
	}

	@Override
	public Integer getParameterCount() {
		Session session = HibernateUtil.getSession();
		parameterDao.setSession(session);

		Integer result = parameterDao.getEntityCount();

		session.close();
		return result;
	}

}
